// swbatch.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include "objbase.h"
#include <atlbase.h>

//Import the SolidWorks type library
#import "C:\Program Files\SolidWorks\sldworks.tlb" raw_interfaces_only, raw_native_types, no_namespace, named_guids 
//Import the SolidWorks constant type library    
#import "C:\Program Files\SolidWorks\swconst.tlb"  raw_interfaces_only, raw_native_types, no_namespace, named_guids 

using namespace std;

/**	The main that executes to initialize SWX without a GUI, load a model and query the model.
	\author Ganeshram Iyer
	\date 04-10-2008
*/
int _tmain(int argc, _TCHAR* argv[])
{
	CoInitialize(NULL);
	CComPtr<ISldWorks> swApp=NULL; 
	CComPtr<IModelDoc2> swModel;
	CComPtr<IComponent2> swComponent;
	CComPtr<IAssemblyDoc> swAssemblyDoc; 
	bool bDone;
	HRESULT hres = NOERROR;

	try
	{
		hres = swApp.CoCreateInstance(__uuidof(SldWorks), NULL, CLSCTX_LOCAL_SERVER);
		if (hres != S_OK) throw 0;
		bDone = true;
		IModelDoc* swModel = NULL;

		if( swApp->put_Visible(FALSE) == S_OK ) {
			if( swApp->DocumentVisible(FALSE, swDocPART) == S_OK ) {
				long fileerror;
				/*long filewarning;

				if( (swApp->OpenDoc6(L"C:\\cygwin\\home\\ganesh\\downloads\\imagecom\\batch\\camtest.sldprt", swDocPART, swOpenDocOptions_Silent, L"Default", &fileerror, &filewarning, &swModel) == S_OK) ) */
				CComBSTR sFileName(L"C:\\cygwin\\home\\ganesh\\downloads\\development\\swbatch\\Debug\\camtest.sldprt");
				CComBSTR sDefaultConfiguration(L"Default");
				if( swApp->IOpenDocSilent(sFileName, swDocPART, &fileerror, &swModel) == S_OK )
				{
					if( swModel != NULL ) {
						IPartDoc *part;
						hres = swModel->QueryInterface(IID_IPartDoc, (LPVOID *)&part);
						if( swModel->put_Visible(FALSE) == S_OK ) {
							CComPtr<IFeature> swfeat;
							if( part->IFirstFeature(&swfeat) == S_OK ) {
								CComBSTR name;
								swfeat->get_Name(&name);
								MessageBox(NULL, name, name, MB_OK);
								if( swModel->Quit() == S_OK ) {
									if( swApp->ExitApp() == S_OK ) {
										wcout << "Exiting gracefully" << endl;
									}
									else {swApp->ExitApp(); wcout << "Exiting again?!?" << endl;}
								}
							}
						}
					}
					else {
						wcout << "Model did not open successfully" << endl;
						swApp->ExitApp();
					}
				}
				else{
					wcout << "Model not opened" << endl;
				}
			}
		}
	}
	catch (int)
	{
		printf("Error starting or attaching to a SolidWorks session.");
		swApp = NULL; 
		swModel = NULL;
		swComponent = NULL;
		swAssemblyDoc = NULL;
		CoUninitialize();
		return 1;
	}

	swApp = NULL; 
	swModel = NULL;
	swComponent = NULL;
	swAssemblyDoc = NULL;
	swApp.Release();
	CoUninitialize();
	return 0;
}

